﻿namespace LogManager.TestUtility
{
    using System.DirectoryServices.AccountManagement;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public static class UserManagement
    {
        public static void CreateLocalUserAccount(string userName, string userPassword)
        {
            // set up machine-level context
            using (PrincipalContext ctx = new PrincipalContext(ContextType.Machine))
            {
                // create new user
                UserPrincipal newUser = new UserPrincipal(ctx);

                // set some properties
                newUser.SamAccountName = userName;
                newUser.DisplayName = "Testuser " + userName;
                newUser.SetPassword(userPassword);

                // define new user to be enabled and password never expires
                newUser.Enabled = true;
                newUser.PasswordNeverExpires = true;

                // save new user
                newUser.Save();
            }
        }

        public static void DeleteIfExists(string userName)
        {
            // set up machine-level context
            using (PrincipalContext ctx = new PrincipalContext(ContextType.Machine))
            {
                // this is very slow +30 sec
                // var user = UserPrincipal.FindByIdentity(ctx, IdentityType.Name, userName);

                var user = new UserPrincipal(ctx);
                user.Name = userName;
                var searcher = new PrincipalSearcher(user);
                user = searcher.FindOne() as UserPrincipal;
           
                if (user != null)
                {
                    user.Delete();
                }
            }
        }
    }
}
